package com.alu4r.atcrowdfunding.manager.controller;


import com.alu4r.atcrowdfunding.VO.Data;
import com.alu4r.atcrowdfunding.bean.Permission;
import com.alu4r.atcrowdfunding.bean.Role;
import com.alu4r.atcrowdfunding.controller.BaseController;
import com.alu4r.atcrowdfunding.manager.service.PermissionService;
import com.alu4r.atcrowdfunding.manager.service.RoleService;
import com.alu4r.atcrowdfunding.util.JsonMessageResult;
import com.alu4r.atcrowdfunding.util.PermissionTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

    @Autowired
    RoleService roleService;

    @Autowired
    PermissionService permissionService;


    @ResponseBody
    @RequestMapping("/doAssignPermission")
    public JsonMessageResult doAssignPermission(@RequestParam("roleId") Integer roleId, Data data){
        System.out.println("分配许可"+roleId);
        for (Integer id : data.getIds()) {
            System.out.println("permission"+id);
        }
        JsonMessageResult jsonMessageResult;
        boolean isSuccess = roleService.saveAssignPermission(roleId,data);
        if(isSuccess){
            jsonMessageResult = JsonMessageResult.success();
        }else {
            jsonMessageResult = JsonMessageResult.fail();
        }
        return jsonMessageResult;
    }


    @ResponseBody
    @RequestMapping("/doAsync")
    public Object doAsync(@RequestParam("roleId") Integer roleId){
        System.out.println("进入到许可分配树");

        List<Permission> allPermission = null;
        List<Integer> permissionsForRole = null;
        try {
            allPermission = permissionService.queryAllPermission();
            //根据角色id获取角色之间分配过的许可
            permissionsForRole = permissionService.queryPermissionIdByRoleId(roleId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return PermissionTree.getCheckedTree(allPermission,permissionsForRole);
    }

    @ResponseBody
    @RequestMapping("/doQueryAllRole")
    public Object doQueryAllRole(){
        start();
        List<Role> roles = roleService.queryAllRole();
        param("success",true);
        param("roles",roles);
        success(true);
        return end();
    }

}
